package com.example.tcpLearn.tcp5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 多用户聊天室：服务端
 */
public class Server {

    public static List<Socket> onLineSocketList = new ArrayList<>();

    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        ServerSocket serverSocket = new ServerSocket(9999);

        while (true) {
            /**
             * Listens for a connection to be made to this socket and accepts it.
             * The method blocks until a connection is made.
             */
            Socket socket = serverSocket.accept();
            System.out.println("服务端接收到一个客户端连接：" + socket.getRemoteSocketAddress());
            onLineSocketList.add(socket);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        /**
                         * 输入
                         */
                        InputStream inputStream = socket.getInputStream();
                        DataInputStream dataInputStream = new DataInputStream(inputStream);
                        while (true) {
                            try {
                                String read = dataInputStream.readUTF();
                                System.out.println("服务端接收到客户端" + socket.getRemoteSocketAddress() + "发送的数据：" + read);
                                System.out.println("=========================");
                                for (Socket socketList : onLineSocketList) {
                                    /**
                                     * 输出
                                     */
                                    OutputStream outputStream = socketList.getOutputStream();
                                    DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                                    dataOutputStream.writeUTF(socket.getRemoteSocketAddress() + "说" + read);
                                    dataOutputStream.flush();
                                }
                            } catch (IOException e) {
                                System.out.println("客户端" + socket.getRemoteSocketAddress() + "已经断开连接");
                                onLineSocketList.remove(socket);
                                dataInputStream.close();
                                socket.close();
                                break;
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }

    }

}
